package com.buli.blmall.generator.core;

import com.alibaba.fastjson2.util.DateUtils;
import com.buli.blmall.generator.config.GeneratorConfig;
import com.buli.blmall.generator.metadata.TableInfo;
import com.buli.blmall.generator.metadata.TableInfo.TableField;
import org.apache.velocity.VelocityContext;

import java.util.*;

/**
 * @author xiang.gao
 * @date 2024/12/11 14:04
 */
public class ContextLoader {

    public static VelocityContext loadContext(TableInfo tableInfo, GeneratorConfig generatorConfig) {

        VelocityContext velocityContext = new VelocityContext();
        velocityContext.put("author", generatorConfig.getAuthor());
        velocityContext.put("date", DateUtils.format(new Date(), generatorConfig.getCommentDate()));
        velocityContext.put("swagger", generatorConfig.isSwagger());
        velocityContext.put("packageName", String.format("%s.%s", generatorConfig.getBasePackage(), generatorConfig.getMoudleName()));
        velocityContext.put("moudleName", generatorConfig.getMoudleName());

        velocityContext.put("business", generatorConfig.getBusiness());
        velocityContext.put("entity", tableInfo.getEntityName());
        velocityContext.put("objectName", tableInfo.getObjectName());
        velocityContext.put("tableName", tableInfo.getName());

        Set<String> importList = new TreeSet<>();
        List<Map<String, Object>> columnList = new LinkedList<>();
        for (TableField tableField : tableInfo.getTableFieldList()) {
            if (tableField.getJavaType().equals("Date")) {
                importList.add("java.util.Date");
            }
            Map<String, Object> columnMap = new HashMap<>(5);
            columnMap.put("name", tableField.getName());
            columnMap.put("javaType", tableField.getJavaType());
            columnMap.put("comment", tableField.getComment());
            columnMap.put("javaField", tableField.getJavaField());
            columnMap.put("primaryKey", tableField.isPrimaryKey());
            columnList.add(columnMap);
        }

        velocityContext.put("columns", columnList);
        velocityContext.put("importList", importList);
        return velocityContext;
    }

}
